package com.xsherl.leetcode.solution;

public class RemoveDuplicatesFromSortedArray2 {

    /**
     * 假设n[1:k]是已经移除重复的子数组，那么如果 t > k 并且 n[t] == n[k - 2]，那么n[t]就一定是要移除的元素
     */
    public int removeDuplicates(int[] nums) {
        if (nums.length < 2){
            return nums.length;
        }
        int left = 2;
        for (int i = 2; i < nums.length; ++i){
            if (nums[i] != nums[left - 2]){
                nums[left] = nums[i];
                left++;
            }
        }
        return left;
    }

    public static void main(String[] args) {
        int[] nums = {1,1,1,2,2,2,2,3};
        int len = new RemoveDuplicatesFromSortedArray2().removeDuplicates(nums);
        for (int i = 0; i < len; i++) {
            System.out.print(nums[i] + ", ");
        }
    }
}
